from rest_framework.serializers import ModelSerializer
from  apps.users.models import User
from  rest_framework.pagination import PageNumberPagination
from rest_framework.views import Response
from collections import OrderedDict

class UserPageNumberPagination(PageNumberPagination):
    """用户列表分页类"""
    page_size=5
    page_size_query_param  = 'pagesize'
    max_page_size = 20

    #设置分页类返回指定数据
    def get_paginated_response(self, data):
        return Response(OrderedDict([
            ('count', self.page.paginator.count),
            ('lists', data),
            ('page',self.page.number),
            ('pages',self.page.paginator.num_pages),
            ('pagesize',self.page.paginator.per_page)
        ]))

class UserModelSerializer(ModelSerializer):
    """用户列表序列化器"""
    class Meta:
        model =User
        fields=('username','mobile','email','id','password')
        extra_kwargs = {
            'password': {'write_only':True} #write_only表明该字段仅用于反序列化输入。在序列化输出时忽略该字段。
        }

    def create(self, validated_data):
        """重写序列化器的保存方法"""
        return User.objects.create_user(**validated_data)



